package concordia.comp6231.model;

import java.util.HashMap;
import java.util.Map;

public class Show {
	
	public final int MAX_TICKETS = 100;
	
	/**
	 * identifies a {@link Show} instance.
	 * A Show is identified by a unique id like MTL175, where the first three characters identify the box office, 
	 * and last three digits specify the show.
	 */
	private String showID;
	private Map<String, Reservation> reservations;
	private int availableTicketsCount;

	public Show(String showID) {
		setShowID(showID);
		reservations = new HashMap<String, Reservation>();
		availableTicketsCount = MAX_TICKETS;
	}
	
	public String getShowID() {
		return showID;
	}

	public void setShowID(String showID) {
		this.showID = showID;
	}
	
	public int getAvailableTicketsCount() {
		return availableTicketsCount;
	}
	
	public Iterable<Reservation> reservations() { 
		return reservations.values();
	}
	
	public int getCustomerReservations(String customerID) {
		if (reservations.containsKey(customerID)) {
			Reservation reservation = reservations.get(customerID);
			int currentNumberOfTicket = reservation.getNumberOfTickets();
			return currentNumberOfTicket;
		} else {
			return 0;
		}
	}
	
	public void addReservation(Customer customer, int numberOfTickets) {
		if (numberOfTickets > availableTicketsCount) {
			throw new IllegalStateException("Number of tickets requested is higher than current available ticket: " + availableTicketsCount);
		}
		// concurrent access should be considered here
		Reservation reservation;
		if (reservations.containsKey(customer.getCustomerID())) {
			reservation = reservations.get(customer.getCustomerID());
			int currentNumberOfTicket = reservation.getNumberOfTickets();
			reservation.setNumberOfTickets(currentNumberOfTicket + numberOfTickets);
		} else {
			reservation = new Reservation(this, customer, numberOfTickets);
			reservations.put(customer.getCustomerID(), reservation);
		}
		availableTicketsCount = availableTicketsCount - numberOfTickets;
		// update file
	}
	
	public void cencelReservation(Customer customer, int numberOfTickets) {
		Reservation reservation;
		if (reservations.containsKey(customer.getCustomerID())) {
			reservation = reservations.get(customer.getCustomerID());
			int currentNumberOfTicket = reservation.getNumberOfTickets();
			if (numberOfTickets > currentNumberOfTicket) {
				throw new IllegalStateException("Number of tickets to cancel is higher than current reserved tickets: " + currentNumberOfTicket);
			} else {
				availableTicketsCount = availableTicketsCount + numberOfTickets;
				reservation.setNumberOfTickets(currentNumberOfTicket - numberOfTickets);
			}
		} else {
			throw new IllegalStateException("Client does not have any reservation");
		}
	}
	
}
